package com.gumball.context;

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

import com.gumball.server.GumballMachineRemote;
import com.gumball.states.HasQuarterState;
import com.gumball.states.NoQuarterState;
import com.gumball.states.SoldOutState;
import com.gumball.states.SoldState;
import com.gumball.states.State;
import com.gumball.states.WinnerState;

public class GumballMachine extends UnicastRemoteObject implements
		GumballMachineRemote {
	/**
	 * 
	 */
	private static final long serialVersionUID = -4121761789262640978L;
	private State soldOutState;
	private State noQuarterState;
	private State hasQuarterState;
	private State soldState;
	private State winnerState;

	private State state = noQuarterState;
	private int count;
	private String location;

	public GumballMachine(String location, int numberGumballs)
			throws RemoteException {
		soldOutState = new SoldOutState(this);
		noQuarterState = new NoQuarterState(this);
		hasQuarterState = new HasQuarterState(this);
		soldState = new SoldState(this);
		winnerState = new WinnerState(this);
		this.location = location;
		this.count = numberGumballs;

		if (numberGumballs > 0) {
			state = noQuarterState;
		}
	}

	public void insertQuarter() {
		state.insertQuater();
	}

	public void ejectQuarter() {
		state.ejectQuater();
	}

	public void turnCrank() {
		state.turnCrank();
		state.dispense();
	}

	public State getState() {
		return state;
	}

	public void setState(State state) {
		this.state = state;
	}

	public State getSoldOutState() {
		return soldOutState;
	}

	public State getNoQuarterState() {
		return noQuarterState;
	}

	public State getHasQuarterState() {
		return hasQuarterState;
	}

	public State getSoldState() {
		return soldState;
	}

	public int getCount() {
		return count;
	}

	public void releaseBall() {
		System.out.println("A gumball comes rolling out the slot...");
		if (count != 0) {
			count--;
		}
	}

	public State getWinnerState() {
		return winnerState;
	}

	@Override
	public String getLocation() throws RemoteException {
		return location;
	}

	public String toString() {
		return "Mighty Gumball, Inc.\n"
				+ "Java-enables Standing Gumball Model #2013\n" + "Invetory: "
				+ getCount() + " gumballs\n" + "Machine is " + getState();
	}
}
